<?php

namespace EthanZ\HyperfExt\Utils;

use EthanZ\HyperfExt\Common\TraceEntity;
use EthanZ\HyperfExt\Constants\Code;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface as ResInterface;

/**
 * 响应类
 */
class Response
{


    /**
     * 返回
     *
     * @param mixed $data
     * @param array $enum
     * @param int   $isRpc
     *
     * @return array|ResInterface
     */
    public static function show(mixed $data = null, array $enum = Code::SUCCESS, int $isRpc = 0): array|ResInterface
    {
        $data = [
            'code'    => $enum[0],
            'message' => $enum[1],
            'data'    => $data,
        ];

        // 获取链路信息.
        if (env('APP_ENV') !== 'prod') {
            $data['debugData'] = TraceEntity::getInstance()->getDebugData();
        }

        if ($isRpc) {
            return $data;
        }

        $resultData = json_encode($data, JSON_UNESCAPED_UNICODE);

        /** @var ResponseInterface $response */
        $response = make(ResponseInterface::class);

        return $response->withStatus(200)->withBody(new SwooleStream($resultData));
    }
}
